package com.web.music.portal.mvc;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import com.web.music.interfaces.AlbumService;
import com.web.music.interfaces.ArtistService;
import com.web.music.interfaces.GenreService;
import com.web.music.model.Genre;
import com.web.music.model.Album;
import com.web.music.model.Artist;


public class DeleteGenreController extends DeleteController {

	// the following three parameters have to be specified in Spring configuration file
	// \lab02-music\lab02-music-portal\src\main\webapp\WEB-INF\music-servlet.xml
	
	private GenreService genreService;
	private AlbumService albumService;
	private ArtistService artistService;
	
	private boolean checkGenresList(Genre genre, List<Genre> genres) {
		for (Genre g : genres) {
			if (g.getId().equals(genre.getId())) {
				return true;
			}
		}
		return false;
	}
	
	private boolean existsGenreAlbums(Genre genre){
		List<Album> albums = albumService.findAll();
		for (Album a : albums) {
			List<Genre> genres = a.getGenres();
			if (checkGenresList(genre, genres)) {
				return true;
			}
		}
		return false;		
	}
	private boolean existsGenreArtists(Genre genre){
		List<Artist> artists = artistService.findAll();
		for (Artist a : artists) {
			if (checkGenresList(genre, a.getGenres())) {
				return true;
			}
		}
		return false;		
	}
	
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) 
	throws Exception 
	{
		Long id = Long.parseLong(request.getParameter("id"));
		Genre genre = genreService.getById(id);

		if (existsGenreAlbums(genre) || existsGenreArtists(genre)) {
			ModelAndView result = new ModelAndView("delete_errors");		
			return result;
		}		
		
		return super.handleRequestInternal(request, response);
	}

	public GenreService getGenreService() {
		return genreService;
	}

	public void setGenreService(GenreService genreService) {
		this.genreService = genreService;
	}


	public AlbumService getAlbumService() {
		return albumService;
	}

	public void setAlbumService(AlbumService albumService) {
		this.albumService = albumService;
	}

	public ArtistService getArtistService() {
		return artistService;
	}

	public void setArtistService(ArtistService artistService) {
		this.artistService = artistService;
	}
		
}
